package Solutions;

/**
 * @Classname CompressString
 * @Description TODO
 * @Date 2021/6/13 15:44
 * @Created by LengDanran
 *
 */
public class CompressString {

    /***
     * 执行结果：
     * 通过
     * 显示详情
     *
     * 添加备注
     * 执行用时：5 ms, 在所有 Java 提交中击败了73.62% 的用户
     * 内存消耗：38.1 MB, 在所有 Java 提交中击败了76.11% 的用户
     */
    public String compressString(String S) {
        if (S.length() <= 1) return S;
        StringBuilder sb = new StringBuilder();
        char tmp = S.charAt(0);
        sb.append(tmp);
        int count = 0;
        for (int i = 1; i < S.length(); i++) {
            if (S.charAt(i) == tmp) {
                count++;
            } else {
                sb.append((count + 1));
                tmp = S.charAt(i);
                count = 0;
                sb.append(tmp);
            }
        }
        sb.append((count + 1));
        if (S.length() > sb.toString().length()) return sb.toString();
        else return S;
    }

    public static void main(String[] args) {
        System.out.println(new CompressString().compressString("acaab"));
    }

}
